package models

import (
	"github.com/jinzhu/gorm"
	"kop/modules/guild/entity"
	"kop/pb"
	"kop/util/date"
	"time"
)

func GetMembers(dB *gorm.DB, guildID int32) []*pb.GuildMember {

	var result []*pb.GuildMember
	var data []entity.Member
	if err := dB.Where(entity.Member{GuildID: guildID}).Limit(100).Find(&data).Error; err != nil {
		panic(err)
	}

	for _, v := range data {

		result = append(result, buildPbMember(v))
	}

	return result
}

func CreateMember(dB *gorm.DB, roleID, guildID int32, position pb.GuildPosition, points int32) *pb.GuildMember {

	var data = entity.Member{
		RoleID:    roleID,
		GuildID:   guildID,
		Position:  position,
		Points:    points,
		BuildType: pb.GuildBuildType_GuildNotBuild,
	}

	if err := dB.Create(&data).Error; err != nil {
		panic(err)
	}

	return buildPbMember(data)
}

func GetMember(dB *gorm.DB, roleID int32) (*pb.GuildMember, bool) {

	var data = entity.Member{
		RoleID: roleID,
	}

	if err := dB.First(&data).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, false
		}
	}

	return buildPbMember(data), true
}

func SaveMember(dB *gorm.DB, member *pb.GuildMember) error {

	var data = entity.Member{
		RoleID:    member.RoleID,
		GuildID:   member.GuildID,
		Position:  member.Position,
		Points:    member.Points,
		Points2:   member.Points2,
		BuildType: member.BuildType,
		BuildDate: member.BuildDate,
	}

	return dB.Save(&data).Error
}

func DelMemberByGuildID(dB *gorm.DB, guildID int32) error {

	return dB.Where(entity.Member{GuildID: guildID}).Delete(&entity.Member{}).Error
}

func DelMember(dB *gorm.DB, roleID int32) error {

	var data = entity.Member{RoleID: roleID}
	return dB.Delete(&data).Error
}

func UpdateOnlineTime(dB *gorm.DB, roleID int32) error {

	return dB.Table("members").Where("role_id = ?", roleID).Update("online_time", time.Now()).Error
}

func buildPbMember(data entity.Member) *pb.GuildMember {

	var member = pb.GuildMember{
		RoleID:     data.RoleID,
		GuildID:    data.GuildID,
		Position:   data.Position,
		Points:     data.Points,
		Points2:    data.Points2,
		BuildType:  data.BuildType,
		BuildDate:  data.BuildDate,
		OnlineTime: data.OnlineTime.Unix(),
	}

	if data.BuildDate != date.Date(time.Now()) {
		member.BuildType = pb.GuildBuildType_GuildNotBuild
	}

	return &member
}
